用法:函式名.call(指定的this變數(參數))。
var myName = '真心鎮大冒險';
var family = {
myName: '小明家',
}
function fn(para1, para2) {
console.log(this, typeof this, para1, para2);
}
fn(1, 2);
fn.call(family, 1, 2);
解:
let obj = {};
function foo() {
console.log(this);
}
foo(); // "Window{}"
foo.call(obj); // Object{}
用法:函式名.apply(指定的this變數[參數])。
var myName = '真心鎮大冒險';
var family = {
myName: '小明家',
}
function fn(para1, para2) {
console.log(this, typeof this, para1, para2);
}
fn(1, 2);
fn.apply(family, [3, 4]);
let obj = {};
function foo() {
console.log(this);
}
foo(); // "Window{}"
foo.apply(obj); // Object{}
let obj = {};
function foo(a, b) {
console.log(this, a, b);
}
foo.call(obj, 1, 2); // Object{} 1 2
foo.apply(obj, [1, 2]); // Object{} 1 2
此模式被稱為硬綁定(hard binding) 指的是綁定既明確又不會意外變回預設的綁定。
var myName = '真心鎮大冒險';
var family = {
myName: '小明家',
}
function fn(para1, para2) {
console.log(this, typeof this, para1, para2);
}
fn(1, 2);
var fn2 = fn.bind(family, '小明');
fn2(1);
參考文章:
JavaScript 的 this:https://chupainotebook.blogspot.com/2019/09/javascript-this.html